package com.liyuxiang.graph.controller;

import com.alibaba.cloud.ai.graph.CompiledGraph;
import com.alibaba.cloud.ai.graph.NodeOutput;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.async.AsyncGenerator;
import com.alibaba.cloud.ai.graph.exception.GraphStateException;
import com.liyuxiang.graph.context.DiagnosisContext;
import com.liyuxiang.graph.entity.EnhancedAiResponse;
import com.liyuxiang.graph.entity.SymptomCollectionForm;
import com.liyuxiang.graph.service.DiagnosisContextService;
import com.liyuxiang.graph.service.QuickSelectionService;
import com.liyuxiang.graph.service.SymptomFormGeneratorService;
import com.liyuxiang.graph.stream.GraphStreamProcessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/diagnosis")
public class DiagnosisController {

    private static final Logger logger = LoggerFactory.getLogger(DiagnosisController.class);

    private final CompiledGraph compiledGraph;
    private final CompiledGraph streamCompiledGraph;
    private final DiagnosisContextService contextService;
    private final QuickSelectionService quickSelectionService;
    private final SymptomFormGeneratorService formGeneratorService;
    private final ObjectMapper objectMapper;

    public DiagnosisController(@Qualifier("diagnosisGraph") StateGraph stateGraph,
                               @Qualifier("streamDiagnosisGraph") StateGraph streamStateGraph,
                               DiagnosisContextService contextService,
                               QuickSelectionService quickSelectionService,
                               SymptomFormGeneratorService formGeneratorService,
                               ObjectMapper objectMapper) throws GraphStateException {
        this.compiledGraph = stateGraph.compile();
        this.streamCompiledGraph = streamStateGraph.compile();
        this.contextService = contextService;
        this.quickSelectionService = quickSelectionService;
        this.formGeneratorService = formGeneratorService;
        this.objectMapper = objectMapper;
        logger.info("智能问诊图和流式图已编译完成");
    }

    @PostMapping("/chat")
    public Map<String, Object> chat(@RequestBody Map<String, Object> request) {
        String query = (String) request.getOrDefault("query", "");
        String userId = (String) request.getOrDefault("userId", UUID.randomUUID().toString());
        String threadId = (String) request.getOrDefault("threadId", "session_" + userId);
        Boolean isNewSession = (Boolean) request.getOrDefault("isNewSession", false);

        logger.info("智能问诊 - 用户ID: {}, 线程ID: {}, 查询: {}, 新会话: {}", userId, threadId, query, isNewSession);

        // 获取或创建诊断上下文
        DiagnosisContext context;
        if (isNewSession) {
            // 完全清理会话（包括ChatMemory和诊断上下文）
            contextService.clearCompleteSession(threadId);
            context = new DiagnosisContext(userId, threadId);
            logger.info("创建新会话上下文 - 用户ID: {}, 线程ID: {}", userId, threadId);
        } else {
            // 获取或创建上下文
            context = contextService.getOrCreateContext(userId, threadId);
        }

        // 首先添加用户输入到上下文并保存
        context.addConversationHistory("用户: " + query);
        contextService.saveContext(context);

        logger.info("用户输入已添加到对话历史 - 线程ID: {}, 当前历史长度: {}",
                threadId, context.getConversationHistory().size());

        // 重新获取更新后的上下文，确保传递给Graph的是最新的对话历史
        DiagnosisContext updatedContext = contextService.getContext(threadId).orElse(context);

        RunnableConfig runnableConfig = RunnableConfig.builder().threadId(threadId).build();

        // 从更新后的上下文构建输入参数
        Map<String, Object> inputMap = new HashMap<>();
        inputMap.put("query", query);
        inputMap.put("userId", userId);
        inputMap.put("threadId", threadId);
        inputMap.put("conversationHistory", updatedContext.getConversationHistory()); // 使用更新后的历史
        inputMap.put("symptoms", updatedContext.getSymptoms());
        inputMap.put("questionCount", updatedContext.getQuestionCount());
        inputMap.put("intentType", updatedContext.getIntentType());
        inputMap.put("shouldContinue", updatedContext.getShouldContinue());
        inputMap.put("isCompleted", updatedContext.getIsCompleted());

        logger.info("传递给Graph的对话历史长度: {}", updatedContext.getConversationHistory().size());

        try {
            Optional<OverAllState> result = this.compiledGraph.invoke(inputMap, runnableConfig);
            Map<String, Object> response = result.map(OverAllState::data).orElse(new HashMap<>());

            // 更新上下文（使用更新后的context）
            updateContextFromResponse(updatedContext, response);
            contextService.saveContext(updatedContext);

            logger.info("智能问诊完成 - 用户ID: {}, 结果: {}", userId, response.get("response"));

            return response;
        } catch (Exception e) {
            logger.error("智能问诊执行失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "系统暂时无法处理您的请求，请稍后重试");
            return errorResponse;
        }
    }

    /**
     * 智能合并对话历史，避免丢失用户输入
     */
    private void mergeConversationHistory(DiagnosisContext context, java.util.List<String> responseHistory) {
        java.util.List<String> currentHistory = context.getConversationHistory();

        logger.info("合并对话历史 - 当前长度: {}, 响应长度: {}",
                currentHistory.size(), responseHistory.size());

        // 只添加新的内容，避免重复
        for (String historyItem : responseHistory) {
            if (!currentHistory.contains(historyItem)) {
                // 检查是否是新的助手回复
                if (historyItem.startsWith("助手:") &&
                        !currentHistory.isEmpty() &&
                        !currentHistory.get(currentHistory.size() - 1).equals(historyItem)) {
                    context.addConversationHistory(historyItem);
                    logger.info("添加新的对话历史项: {}", historyItem);
                }
            }
        }
    }

    /**
     * 从响应中更新上下文
     */
    @SuppressWarnings("unchecked")
    private void updateContextFromResponse(DiagnosisContext context, Map<String, Object> response) {
        // 更新意图类型
        if (response.containsKey("intentType")) {
            context.setIntentType((String) response.get("intentType"));
        }

        // 更新症状信息
        if (response.containsKey("symptoms")) {
            Map<String, Object> symptoms = (Map<String, Object>) response.get("symptoms");
            if (symptoms != null) {
                context.setSymptoms(symptoms);
            }
        }

        // 更新对话历史 - 保留用户输入，只添加AI回复
        if (response.containsKey("conversationHistory")) {
            java.util.List<String> responseHistory = (java.util.List<String>) response.get("conversationHistory");
            if (responseHistory != null && !responseHistory.isEmpty()) {
                // 不直接覆盖，而是智能合并对话历史
                mergeConversationHistory(context, responseHistory);
            }
        }

        // 添加AI回复到对话历史
        if (response.containsKey("response")) {
            String aiResponse = (String) response.get("response");
            context.addConversationHistory("助手: " + aiResponse);
            logger.info("助手AI回复已添加到对话历史 - 线程ID: {}, 历史长度: {}",
                    context.getThreadId(), context.getConversationHistory().size());
        }

        // 更新问题计数
        if (response.containsKey("questionCount")) {
            context.setQuestionCount((Integer) response.get("questionCount"));
        }

        // 更新继续标志
        if (response.containsKey("shouldContinue")) {
            context.setShouldContinue((Boolean) response.get("shouldContinue"));
        }

        // 更新完成状态
        if (response.containsKey("isCompleted")) {
            context.setIsCompleted((Boolean) response.get("isCompleted"));
        }

        // 更新推荐科室
        if (response.containsKey("recommendedDepartment")) {
            context.setRecommendedDepartment((String) response.get("recommendedDepartment"));
        }

        // 更新科室ID和科室IDs数组
        if (response.containsKey("deptId")) {
            Object deptIdObj = response.get("deptId");
            if (deptIdObj instanceof Long) {
                logger.info("主要推荐科室ID: {}", deptIdObj);
            }
        }
        
        // 处理科室IDs数组
        if (response.containsKey("deptIds")) {
            Object deptIdsObj = response.get("deptIds");
            if (deptIdsObj instanceof Long[]) {
                Long[] deptIds = (Long[]) deptIdsObj;
                logger.info("推荐的多个科室IDs: {}, 数量: {}", java.util.Arrays.toString(deptIds), deptIds.length);
            } else if (deptIdsObj instanceof java.util.List) {
                @SuppressWarnings("unchecked")
                java.util.List<Long> deptIdsList = (java.util.List<Long>) deptIdsObj;
                logger.info("推荐的多个科室IDs: {}, 数量: {}", deptIdsList, deptIdsList.size());
            }
        }

        // 更新最后回复
        if (response.containsKey("response")) {
            context.setLastResponse((String) response.get("response"));
        }
    }

    /**
     * 获取诊断上下文信息
     */
    @GetMapping("/context/{threadId}")
    public Map<String, Object> getContext(@PathVariable String threadId) {
        logger.info("获取诊断上下文 - 线程ID: {}", threadId);

        Optional<DiagnosisContext> contextOpt = contextService.getContext(threadId);
        Map<String, Object> response = new HashMap<>();

        if (contextOpt.isPresent()) {
            DiagnosisContext context = contextOpt.get();
            response.put("exists", true);
            response.put("context", context);
            response.put("conversationCount", context.getConversationHistory().size());
            response.put("symptomsCount", context.getSymptoms().size());
            logger.info("找到诊断上下文 - 线程ID: {}, 问题轮次: {}", threadId, context.getQuestionCount());
        } else {
            response.put("exists", false);
            response.put("message", "诊断上下文不存在");
            logger.info("诊断上下文不存在 - 线程ID: {}", threadId);
        }

        return response;
    }

    /**
     * 清除诊断上下文
     */
    @DeleteMapping("/context/{threadId}")
    public Map<String, Object> clearContext(@PathVariable String threadId) {
        logger.info("清除诊断上下文 - 线程ID: {}", threadId);

        // 使用完全清理方法，确保ChatMemory也被清理
        contextService.clearCompleteSession(threadId);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "诊断上下文和对话历史已完全清除");

        return response;
    }

    /**
     * 流式智能问诊接口 - 实时返回AI响应
     */
    @GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> chatStream(
            @RequestParam("query") String query,
            @RequestParam(value = "userId", defaultValue = "") String userId,
            @RequestParam(value = "threadId", defaultValue = "") String threadId,
            @RequestParam(value = "isNewSession", defaultValue = "false") Boolean isNewSession) {

        // 生成默认ID
        if (userId.isEmpty()) {
            userId = UUID.randomUUID().toString();
        }
        if (threadId.isEmpty()) {
            threadId = "session_" + userId;
        }

        logger.info("流式智能问诊开始 - 用户ID: {}, 线程ID: {}, 查询: {}, 新会话: {}",
                userId, threadId, query, isNewSession);

        // 创建服务器发送事件的Sink
        Sinks.Many<ServerSentEvent<String>> sink = Sinks.many().unicast().onBackpressureBuffer();

        try {
            // 获取或创建诊断上下文
            DiagnosisContext context;
            if (isNewSession) {
                contextService.clearCompleteSession(threadId);
                context = new DiagnosisContext(userId, threadId);
                logger.info("创建新的流式会话上下文 - 用户ID: {}, 线程ID: {}", userId, threadId);
            } else {
                context = contextService.getOrCreateContext(userId, threadId);
            }

            // 添加用户输入到上下文
            context.addConversationHistory("用户: " + query);
            contextService.saveContext(context);

            // 重新获取更新后的上下文
            DiagnosisContext updatedContext = contextService.getContext(threadId).orElse(context);

            // 构建图执行参数
            RunnableConfig runnableConfig = RunnableConfig.builder().threadId(threadId).build();
            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put("query", query);
            inputMap.put("userId", userId);
            inputMap.put("threadId", threadId);
            inputMap.put("conversationHistory", updatedContext.getConversationHistory());
            inputMap.put("symptoms", updatedContext.getSymptoms());
            inputMap.put("questionCount", updatedContext.getQuestionCount());
            inputMap.put("intentType", updatedContext.getIntentType());
            inputMap.put("shouldContinue", updatedContext.getShouldContinue());
            inputMap.put("isCompleted", updatedContext.getIsCompleted());

            logger.info("开始流式执行图 - 线程ID: {}, 输入参数数量: {}", threadId, inputMap.size());

            // 启动流式执行 - 使用流式图
            AsyncGenerator<NodeOutput> streamGenerator = streamCompiledGraph.stream(inputMap, runnableConfig);

            // 创建流式处理器
            GraphStreamProcessor processor = new GraphStreamProcessor(objectMapper);
            processor.processStream(streamGenerator, sink, threadId);

        } catch (Exception e) {
            logger.error("流式智能问诊失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);

            // 发送错误事件
            try {
                Map<String, Object> errorData = Map.of(
                        "type", "error",
                        "threadId", threadId,
                        "error", "系统暂时无法处理您的请求: " + e.getMessage()
                );
                String content = objectMapper.writeValueAsString(errorData);

                ServerSentEvent<String> errorEvent = ServerSentEvent.<String>builder()
                                                                    .id(String.valueOf(System.currentTimeMillis()))
                                                                    .event("error")
                                                                    .data(content)
                                                                    .build();

                sink.tryEmitNext(errorEvent);
            } catch (Exception ex) {
                logger.error("发送错误事件失败: {}", ex.getMessage());
            }

            sink.tryEmitError(e);
        }

        final String finalThreadId = threadId;
        return sink.asFlux()
                   .doOnCancel(() -> logger.info("客户端断开流式连接 - 线程ID: {}", finalThreadId))
                   .doOnError(e -> logger.error("流式响应错误 - 线程ID: {}, 错误: {}", finalThreadId, e.getMessage()))
                   .doOnComplete(() -> logger.info("流式响应完成 - 线程ID: {}", finalThreadId));
    }

    /**
     * POST方式的流式智能问诊接口
     */
    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> chatStreamPost(@RequestBody Map<String, Object> request) {
        String query = (String) request.getOrDefault("query", "");
        String userId = (String) request.getOrDefault("userId", "");
        String threadId = (String) request.getOrDefault("threadId", "");
        Boolean isNewSession = (Boolean) request.getOrDefault("isNewSession", false);

        return chatStream(query, userId, threadId, isNewSession);
    }

    /**
     * 增强的智能问诊接口 - 支持快捷选择
     */
    @PostMapping("/chat/enhanced")
    public EnhancedAiResponse chatEnhanced(@RequestBody Map<String, Object> request) {
        String query = (String) request.getOrDefault("query", "");
        String userId = (String) request.getOrDefault("userId", UUID.randomUUID().toString());
        String threadId = (String) request.getOrDefault("threadId", "session_" + userId);
        Boolean isNewSession = (Boolean) request.getOrDefault("isNewSession", false);

        logger.info("增强智能问诊 - 用户ID: {}, 线程ID: {}, 查询: {}, 新会话: {}", userId, threadId, query, isNewSession);

        try {
            // 先调用标准的chat接口获取AI响应
            Map<String, Object> standardRequest = new HashMap<>();
            standardRequest.put("query", query);
            standardRequest.put("userId", userId);
            standardRequest.put("threadId", threadId);
            standardRequest.put("isNewSession", isNewSession);

            Map<String, Object> aiResult = chat(standardRequest);

            // 检查是否有错误
            if (aiResult.containsKey("error")) {
                EnhancedAiResponse errorResponse = new EnhancedAiResponse();
                errorResponse.setResponse((String) aiResult.get("error"));
                errorResponse.setResponseType(EnhancedAiResponse.ResponseType.TEXT);
                errorResponse.setShowTextInput(true);
                return errorResponse;
            }

            // 获取AI响应和症状信息
            String aiResponse = (String) aiResult.getOrDefault("response", "");
            @SuppressWarnings("unchecked")
            Map<String, Object> symptoms = (Map<String, Object>) aiResult.getOrDefault("symptoms", new HashMap<>());
            Integer questionCount = (Integer) aiResult.getOrDefault("questionCount", 0);
            String intentType = (String) aiResult.getOrDefault("intentType", "有意图");

            logger.info("增强处理 - AI响应长度: {}, 症状数量: {}, 问题轮次: {}",
                    aiResponse.length(), symptoms.size(), questionCount);

            // 使用快捷选择服务增强响应
            EnhancedAiResponse enhancedResponse = quickSelectionService.enhanceWithQuickOptions(
                    aiResponse, symptoms, questionCount, intentType);

            // 添加其他AI分析的元数据
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("questionCount", questionCount);
            metadata.put("intentType", intentType);
            metadata.put("confidence", aiResult.get("confidence"));
            metadata.put("shouldContinue", aiResult.get("shouldContinue"));
            metadata.put("isCompleted", aiResult.get("isCompleted"));
            metadata.put("completeness", aiResult.get("completeness"));
            metadata.put("urgency", aiResult.get("urgency"));
            metadata.put("reasoning", aiResult.get("reason"));

            enhancedResponse.setMetadata(metadata);

            logger.info("增强智能问诊完成 - 用户ID: {}, 响应类型: {}, 选项数量: {}",
                    userId, enhancedResponse.getResponseType(),
                    enhancedResponse.getQuickOptions() != null ? enhancedResponse.getQuickOptions().size() : 0);

            return enhancedResponse;

        } catch (Exception e) {
            logger.error("增强智能问诊失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);

            EnhancedAiResponse errorResponse = new EnhancedAiResponse();
            errorResponse.setResponse("系统暂时无法处理您的请求，请稍后重试");
            errorResponse.setResponseType(EnhancedAiResponse.ResponseType.TEXT);
            errorResponse.setShowTextInput(true);

            Map<String, Object> errorMetadata = new HashMap<>();
            errorMetadata.put("error", e.getMessage());
            errorResponse.setMetadata(errorMetadata);

            return errorResponse;
        }
    }

    /**
     * 批量处理症状数据接口
     */
    @PostMapping("/chat/batch")
    public Map<String, Object> processBatchSymptoms(@RequestBody Map<String, Object> request) {
        String userId = (String) request.getOrDefault("userId", "unknown");
        String threadId = (String) request.getOrDefault("threadId", "session_" + userId);
        Boolean isNewSession = (Boolean) request.getOrDefault("isNewSession", false);
        @SuppressWarnings("unchecked")
        Map<String, Object> symptomData = (Map<String, Object>) request.getOrDefault("symptomData", new HashMap<>());

        logger.info("批量处理症状数据 - 用户ID: {}, 线程ID: {}, 症状数据项数: {}",
                userId, threadId, symptomData.size());

        try {
            // 获取或创建诊断上下文
            DiagnosisContext context = contextService.getOrCreateContext(userId, threadId);

            // 将表单数据转换为文本描述
            String symptomSummary = convertSymptomDataToText(symptomData);

            // 更新上下文症状信息
            context.getSymptoms().putAll(symptomData);
            context.addConversationHistory("用户: " + symptomSummary);
            contextService.saveContext(context);

            logger.info("症状数据已保存到上下文 - 症状总结: {}", symptomSummary);

            // 调用AI进行综合分析和科室推荐
            RunnableConfig runnableConfig = RunnableConfig.builder().threadId(threadId).build();

            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put("query", symptomSummary);
            inputMap.put("userId", userId);
            inputMap.put("threadId", threadId);
            inputMap.put("conversationHistory", context.getConversationHistory());
            inputMap.put("symptoms", context.getSymptoms());
            inputMap.put("questionCount", context.getQuestionCount() + 1);
            inputMap.put("intentType", "有意图");
            inputMap.put("shouldContinue", false); // 表单填写完成，不需要继续询问
            inputMap.put("isCompleted", true); // 标记为已完成
            inputMap.put("batchProcessing", true); // 标记为批量处理

            Optional<OverAllState> result = this.compiledGraph.invoke(inputMap, runnableConfig);
            Map<String, Object> originalResponse = result.map(OverAllState::data).orElse(new HashMap<>());
            
            // 创建可修改的响应Map
            Map<String, Object> response = new HashMap<>(originalResponse);
            
            // 更新上下文
            updateContextFromResponse(context, originalResponse);
            context.setIsCompleted(true); // 设置为已完成
            contextService.saveContext(context);
            
            // 增强响应内容
            String aiResponse = (String) response.getOrDefault("response", "");
            if (aiResponse.isEmpty()) {
                aiResponse = generateDepartmentRecommendation(symptomData);
            }
            
            response.put("response", aiResponse);
            response.put("isCompleted", true);
            response.put("batchProcessed", true);
            response.put("symptomSummary", symptomSummary);

            logger.info("批量症状处理完成 - 用户ID: {}, 推荐结果: {}", userId, aiResponse);

            return response;

        } catch (Exception e) {
            logger.error("批量处理症状数据失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("response", "症状分析过程中出现问题，请稍后重试或联系医务人员获取帮助。");
            errorResponse.put("error", e.getMessage());
            errorResponse.put("isCompleted", false);

            return errorResponse;
        }
    }

    /**
     * 将症状表单数据转换为文本描述
     */
    private String convertSymptomDataToText(Map<String, Object> symptomData) {
        StringBuilder summary = new StringBuilder();
        
        logger.info("转换症状数据 - 接收到的数据: {}", symptomData);

        try {
            // 主要症状描述
            if (symptomData.containsKey("symptom_description")) {
                summary.append("主要症状：").append(symptomData.get("symptom_description")).append("。 ");
            }

            // 疼痛位置
            if (symptomData.containsKey("pain_location")) {
                String location = mapValueToLabel((String) symptomData.get("pain_location"));
                summary.append("疼痛位置：").append(location).append("。 ");
            }

            // 疼痛性质
            if (symptomData.containsKey("pain_type")) {
                String type = mapValueToLabel((String) symptomData.get("pain_type"));
                summary.append("疼痛性质：").append(type).append("。 ");
            }

            // 疼痛程度
            if (symptomData.containsKey("pain_level")) {
                Object painLevel = symptomData.get("pain_level");
                summary.append("疼痛程度：").append(painLevel).append("级（1-10级）。 ");
            }

            // 持续时间
            if (symptomData.containsKey("duration")) {
                String duration = mapValueToLabel((String) symptomData.get("duration"));
                summary.append("持续时间：").append(duration).append("。 ");
            }

            // 伴随症状
            if (symptomData.containsKey("accompanying_symptoms")) {
                @SuppressWarnings("unchecked")
                java.util.List<String> symptoms = (java.util.List<String>) symptomData.get("accompanying_symptoms");
                if (symptoms != null && !symptoms.isEmpty()) {
                    if (symptoms.contains("none")) {
                        summary.append("无其他伴随症状。 ");
                    } else {
                        String accompanyingText = symptoms.stream()
                                                          .map(this::mapValueToLabel)
                                                          .collect(java.util.stream.Collectors.joining("、"));
                        summary.append("伴随症状：").append(accompanyingText).append("。 ");
                    }
                }
            }

            // 诱发因素
            if (symptomData.containsKey("trigger_factors")) {
                String trigger = mapValueToLabel((String) symptomData.get("trigger_factors"));
                summary.append("可能诱因：").append(trigger).append("。 ");
            }

            // 用药情况
            if (symptomData.containsKey("medication_status")) {
                String medication = mapValueToLabel((String) symptomData.get("medication_status"));
                summary.append("用药情况：").append(medication).append("。 ");
            }

        } catch (Exception e) {
            logger.warn("转换症状数据时出现异常: {}", e.getMessage());
            summary.append("用户填写了详细的症状信息表单");
        }

        String result = summary.toString().trim();
        return result.isEmpty() ? "用户提供了症状相关信息" : result;
    }

    /**
     * 将值映射为可读的标签
     */
    private String mapValueToLabel(String value) {
        if (value == null) return "未知";

        // 疼痛位置映射
        Map<String, String> locationMap = Map.of(
                "upper_abdomen", "上腹部",
                "lower_abdomen", "下腹部",
                "left_abdomen", "左腹部",
                "right_abdomen", "右腹部",
                "whole_abdomen", "全腹",
                "other_location", "其他部位"
        );

        // 疼痛性质映射
        Map<String, String> typeMap = Map.of(
                "continuous", "持续性疼痛",
                "intermittent", "间歇性疼痛",
                "paroxysmal", "阵发性疼痛",
                "throbbing", "跳痛",
                "bloating", "胀痛",
                "stabbing", "刺痛"
        );

        // 持续时间映射
        Map<String, String> durationMap = Map.of(
                "just_started", "刚开始(不到1小时)",
                "few_hours", "几个小时",
                "1_2_days", "1-2天",
                "3_7_days", "3-7天",
                "1_2_weeks", "1-2周",
                "over_month", "超过1个月"
        );

        // 伴随症状映射
        Map<String, String> symptomMap = Map.of(
                "none", "无其他症状",
                "nausea", "恶心",
                "vomiting", "呕吐",
                "fever", "发热",
                "diarrhea", "腹泻",
                "constipation", "便秘",
                "dizziness", "头晕"
        );

        // 诱发因素映射
        Map<String, String> triggerMap = Map.of(
                "food_related", "饮食相关",
                "exercise_related", "运动后",
                "work_stress", "工作劳累",
                "emotional", "情绪激动",
                "cold_exposure", "受凉",
                "no_obvious_cause", "无明显诱因"
        );

        // 用药情况映射  
        Map<String, String> medicationMap = Map.of(
                "no_medication", "未用药",
                "painkillers", "止痛药",
                "stomach_medicine", "胃药",
                "chinese_medicine", "中成药",
                "other_medication", "其他药物"
        );

        // 依次尝试各个映射
        return locationMap.getOrDefault(value,
                typeMap.getOrDefault(value,
                        durationMap.getOrDefault(value,
                                symptomMap.getOrDefault(value,
                                        triggerMap.getOrDefault(value,
                                                medicationMap.getOrDefault(value, value))))));
    }

    /**
     * 生成科室推荐（备用逻辑）
     */
    private String generateDepartmentRecommendation(Map<String, Object> symptomData) {
        StringBuilder recommendation = new StringBuilder();

        recommendation.append("根据您提供的症状信息，我为您推荐以下科室：\n\n");

        // 根据症状数据判断推荐科室
        if (symptomData.containsKey("pain_location")) {
            String location = (String) symptomData.get("pain_location");
            if ("upper_abdomen".equals(location)) {
                recommendation.append("🏥 **消化内科** - 推荐指数：⭐⭐⭐⭐⭐\n");
                recommendation.append("上腹部疼痛通常与胃、十二指肠相关疾病有关\n\n");
                recommendation.append("🏥 **普通内科** - 推荐指数：⭐⭐⭐\n");
                recommendation.append("可以进行初步检查和诊断\n\n");
            } else if ("right_abdomen".equals(location)) {
                recommendation.append("🏥 **普通外科** - 推荐指数：⭐⭐⭐⭐⭐\n");
                recommendation.append("右腹部疼痛需要排除阑尾炎等外科疾病\n\n");
                recommendation.append("🏥 **消化内科** - 推荐指数：⭐⭐⭐\n");
                recommendation.append("也可能是消化系统疾病\n\n");
            }
        }

        // 检查是否有发热症状
        if (symptomData.containsKey("accompanying_symptoms")) {
            @SuppressWarnings("unchecked")
            java.util.List<String> symptoms = (java.util.List<String>) symptomData.get("accompanying_symptoms");
            if (symptoms != null && symptoms.contains("fever")) {
                recommendation.append("⚠️ **温馨提示**：您有发热症状，建议优先就诊\n\n");
            }
        }

        // 检查疼痛程度
        if (symptomData.containsKey("pain_level")) {
            Object painLevel = symptomData.get("pain_level");
            if (painLevel instanceof Number && ((Number) painLevel).intValue() >= 7) {
                recommendation.append("🚨 **紧急提醒**：疼痛程度较重，建议尽快就医\n\n");
            }
        }

        recommendation.append("📝 **就诊建议**：\n");
        recommendation.append("• 建议携带相关检查资料\n");
        recommendation.append("• 可提前预约挂号\n");
        recommendation.append("• 如症状加重请及时就医\n\n");

        recommendation.append("💡 **温馨提醒**：以上推荐仅供参考，具体诊断需要专业医生面诊。");

        return recommendation.toString();
    }

    /**
     * 获取症状收集表单接口
     */
    @PostMapping("/symptom-form")
    public SymptomCollectionForm getSymptomForm(@RequestBody Map<String, Object> request) {
        String initialSymptom = (String) request.getOrDefault("initialSymptom", "");
        String userId = (String) request.getOrDefault("userId", "unknown");

        logger.info("生成症状收集表单 - 用户ID: {}, 初始症状: {}", userId, initialSymptom);

        try {
            SymptomCollectionForm form = formGeneratorService.generateSymptomForm(initialSymptom, userId);
            logger.info("症状表单生成成功 - 用户ID: {}, 字段数量: {}", userId, form.getFields().size());
            return form;
        } catch (Exception e) {
            logger.error("症状表单生成失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);

            // 返回默认表单
            SymptomCollectionForm defaultForm = new SymptomCollectionForm();
            defaultForm.setTitle("症状信息收集");
            defaultForm.setDescription("请简单描述您的症状");
            defaultForm.setFields(java.util.List.of());

            return defaultForm;
        }
    }

    /**
     * 将表单数据转换为自然语言查询
     */
    private String buildQueryFromSymptomData(Map<String, Object> symptomData) {
        StringBuilder queryBuilder = new StringBuilder();

        // 主要症状描述
        if (symptomData.containsKey("symptom_description")) {
            String description = (String) symptomData.get("symptom_description");
            if (description != null && !description.trim().isEmpty()) {
                queryBuilder.append(description.trim());
            }
        }

        // 疼痛相关信息
        appendIfPresent(queryBuilder, symptomData, "pain_location", "疼痛位置：");
        appendIfPresent(queryBuilder, symptomData, "pain_type", "疼痛性质：");

        // 疼痛程度（滑动条值）
        if (symptomData.containsKey("pain_level")) {
            Object painLevel = symptomData.get("pain_level");
            if (painLevel != null) {
                queryBuilder.append("，疼痛程度：").append(painLevel).append("级");
            }
        }

        appendIfPresent(queryBuilder, symptomData, "duration", "持续时间：");

        // 伴随症状（多选）
        if (symptomData.containsKey("accompanying_symptoms")) {
            @SuppressWarnings("unchecked")
            java.util.List<String> symptoms = (java.util.List<String>) symptomData.get("accompanying_symptoms");
            if (symptoms != null && !symptoms.isEmpty()) {
                queryBuilder.append("，伴随症状：").append(String.join("、", symptoms));
            }
        }

        appendIfPresent(queryBuilder, symptomData, "trigger_factors", "诱发因素：");
        appendIfPresent(queryBuilder, symptomData, "medication_status", "用药情况：");

        String result = queryBuilder.toString();
        return result.isEmpty() ? "患者描述了相关症状" : result;
    }

    /**
     * 辅助方法：如果字段存在且不为空，则添加到查询中
     */
    private void appendIfPresent(StringBuilder builder, Map<String, Object> data, String key, String prefix) {
        if (data.containsKey(key)) {
            Object value = data.get(key);
            if (value != null) {
                String strValue = value.toString();
                if (!strValue.trim().isEmpty() && !strValue.equals("null")) {
                    builder.append("，").append(prefix).append(strValue);
                }
            }
        }
    }
}